package cn.kuang.service;

import cn.kuang.mapper.ArticleMapper;
import cn.kuang.mapper.ArticleUserMapper;
import cn.kuang.pojo.Article;
import cn.kuang.pojo.ArticleUser;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author 徽州大都督
 * @date 2020/7/24
 */
@Service
@Transactional
public class ArticleService {

    @Autowired
    private ArticleMapper articleMapper;

    @Autowired
    private ArticleUserMapper articleUserMapper;

    public int addArticle(Article article) {

        int insert = articleMapper.insert (article);

        return insert;
    }

    /**
     * 分页查询
     * @param page
     * @param size
     * @return
     */
    public List<Article> findPage(Integer page, Integer size) {
        Page<Article> pag = new Page<> (page,size);
        QueryWrapper<Article> wrapper = new QueryWrapper<> ();

        //按时间排序
        wrapper.orderByDesc ("article_time");
        articleMapper.selectPage (pag,wrapper);
        long total = pag.getTotal ();
        List<Article> articleList = pag.getRecords ();

        //QueryWrapper<ArticleUser> wrapper1 = new QueryWrapper<> ();


        //将总条数传到前台
        articleList.forEach (article -> {


            //根据tid查询评论量
            List<ArticleUser> articleUsers = articleUserMapper.selectList (new QueryWrapper<ArticleUser> ().eq ("tid",article.getTid ()));

            article.setComments (articleUsers.size ());

            article.setTotal (total);
        });

        return articleList;
    }

    public Article findByTid(String tid) {


        Article article = articleMapper.selectById (tid);
        Integer views = article.getViews ();
        article.setViews (views+1);

        //浏览量+1
        articleMapper.updateById (article);

        //评论量
       /* QueryWrapper<ArticleUser> wrapper = new QueryWrapper<> ();
        wrapper.eq ("tid", tid);
        List<ArticleUser> articleUsers = articleUserMapper.selectList (wrapper);

        article.setComments (articleUsers.size ());*/

        return article;
    }
}
